<?php

class Admin_DealsController extends GTL_Action {

    public function init() {
        parent::init();
        /* Initialize action controller here */
        $this->list_sess_unset('controller_deal');
        $this->session_search_key = 'controller_deal';
        $this->session_search_name = 'search_label';
    }

    public function indexAction() {
        $this->_helper->redirector('list', 'deal', 'admin');
    }
	
	public function unsetsessionAction() {
        $pagename = $this->_getParam('pagename');
        unset($_SESSION['_LISTING_SESS']);
        $this->_helper->redirector($pagename, 'deal', 'admin');
    }

    public function listAction() {

        $errorMessage = Array();
        $successmessage = "";
        $where = "";
        $searchtype = "";
        $orderField = 'deal_id';
        $sort = 'asc';

        if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name])) {
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name] = "";
        }
        /* Pagination Login */
        $itemsPerPageReviews = $this->PAGING_PER_PAGE;
        $currentPageReviews = 1;
		
        //PAGING_PER_PAGE

        if ($this->_getParam('page') && $this->_getParam('page') != "") {
            $currentPageReviews = $this->_getParam('page');
        }

        if ($this->_getParam('field') && $this->_getParam('field') != "") {
            $orderField = $this->_getParam('field');
        }

        if ($this->_getParam('sort') && $this->_getParam('sort') != "") {
            $sort = $this->_getParam('sort');
        }

        $offset = ($currentPageReviews - 1) * $itemsPerPageReviews;

        if ($this->_request->isPost()) {
            $postedData = $this->_request->getPost();

            //Multiple Delete Logic 
            if (isset($postedData["multiaction"]) && ($postedData["multiaction"] != "")) {
                $action = trim($postedData["multiaction"]);
                if (isset($postedData["multicheck"]) && count($postedData["multicheck"]) > 0) {
                    $ids = implode(",", $_POST["multicheck"]);
                    $result = $this->deleteAction($_POST["multicheck"]);
                } else {
                    $errorMessage[] = "Please select one checkbox";
                }
            }
			/* Search Facility Over Here */
            if ($postedData["searchtype"] == "") {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = "";
            }
            if (isset($postedData["searchtype"]) && ($postedData["searchtype"] != "")) {
                $searchtype = $postedData["searchtype"];
                $where = "deal_name LIKE '%$searchtype%' ";
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
                $this->view->searchtype = $searchtype;
            }
        } else {

            if (!isset($_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'])) {
                $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = '';
            }
			$searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
            $where = "deal_name LIKE '%$searchtype%' ";
            $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'] = $searchtype;
            $this->view->searchtype = $_SESSION['_LISTING_SESS'][$this->session_search_key][$this->session_search_name]['searchtype'];
        }
		
        //Load deal Model
        $dealModel = new Model_Deals();
        $dealData = $dealModel->fetchDealData($where, $itemsPerPageReviews, $offset, $orderField, $sort);
        //Paginator logiq
        $paginator = new GTL_Paginator();

        $paginator->setItemsPerPage($itemsPerPageReviews);
        $paginator->setItemsTotal($dealModel->getDealCount($where));
        $paginator->setCurrentPage($currentPageReviews);
        $link = $this->view->url(array('controller' => 'deals', 'action' => 'list', 'page' => 'PAGENO'), 'default', false);

        $paginator->paginate($link);
		$GTLOBJ = new GTL_Common();

        $this->view->gtlObj = $GTLOBJ;
        $this->view->paginator = $paginator;
        $this->view->dealData = $dealData;
        $this->view->errorMessage = $errorMessage;
        $this->view->successmessage = $successmessage;
        $this->view->statusArray = $dealModel->getStatusArray();
        $this->view->searchtype = $searchtype;
    }

    public function formAction() {
		
        //Initialize
        $deal_id = '';
        $successmessage = '';
        $errorMessageArray = Array();
        $data = array();
        $dealData = Array();
		$deal_available_to_everyone = "";
        $this->view->mode = 'Add';

        //Load deal Model
        $dealModel = new Model_Deals();
		
		//Load deal Form
        $dealsForm = new Form_Admin_Deals();
		
		//Load client Model
        $clientModel = new Model_Client();
		
		//Load the client array for the select box in form 
        $clientArray = $clientModel->fetchClient();
        $dealsForm->deal_clnt_id->addMultiOptions($clientArray);

        //Load the status array for the select box in form 
        $statusArray = $dealModel->getStatusArray();
        $dealsForm->deal_status->addMultiOptions($statusArray);
		
		//Load the Deal Currency array for the select box in form 
        $dealcurrencyArray = $dealModel->getDealcurrencyArray();
        $dealsForm->deal_currency->addMultiOptions($dealcurrencyArray);
		
		//Load the Deal stage array for the select box in form 
        $dealstageArray = $dealModel->getDealstageArray();
        $dealsForm->deal_stage->addMultiOptions($dealstageArray);
		
		//Load the Deal Type array for the select box in form 
        $dealtypeArray = $dealModel->getDealtypeArray();
        $dealsForm->deal_type->addMultiOptions($dealtypeArray);
		
        //Check for the deal_id Parameter
        $dealData['deal_id'] = $this->_request->getParam('deal_id');
        $deal_id = (!empty($dealData['deal_id'])) ? $dealData['deal_id'] : null;

        if (!empty($deal_id)) {

            //Set the Mode to Edit
            $this->view->mode = 'Edit';
            //Fetch data to be loaded in form 
            $data = $dealModel->fetchEntryById($deal_id); 
			$deal_available_to_everyone = $data['deal_available_to_everyone'];
        }

        //Populate form 
        $this->view->form = $dealsForm->populate($data);
		//echo '<pre>';print_r($data);exit;
        if ($this->getRequest()->isPost()) {
            //Check for Errors
            $postedData = $this->_request->getPost();
            if (!$dealsForm->isValid($postedData)) {
                $errorMessage = $dealsForm->getMessages();
                foreach ($errorMessage as $_err) {
                    foreach ($_err as $_val) {
                        $errorMessageArray[] = $_val;
                    }
                }
            } else {
               
                if (count($errorMessageArray) > 0) {
                    
                } else {

					if ($this->view->mode == 'Add') {
                        $dealData['deal_createddate'] = date('Y-m-d H:i:s');
						$dealData['deal_addedby'] = $this->USER->lgn_id;
                    }
                    //Deal save
                    $dealData['deal_id'] = $deal_id;
                    $dealData['deal_name'] = $postedData['deal_name'];
                    $dealData['deal_stage'] = $postedData['deal_stage'];
					$dealData['deal_currency'] = $postedData['deal_currency'];
					$dealData['deal_income'] = $postedData['deal_income'];
                    $dealData['deal_probability'] = $postedData['deal_probability'];
					$dealData['deal_responsible'] = $this->USER->lgn_id;
					$dealData['deal_startdate'] = date('Y-m-d H:i:s');
					$dealData['deal_enddate'] = date('Y-m-d H:i:s');
					$dealData['deal_type'] = $postedData['deal_type'];
					if (array_key_exists('deal_available_to_everyone', $postedData)) {
						$dealData['deal_available_to_everyone'] = $postedData['deal_available_to_everyone'];
					} else {
						$dealData['deal_available_to_everyone'] = 0;
					}
					$dealData['deal_clnt_id'] = $postedData['deal_clnt_id'];
					$dealData['deal_comment'] = $postedData['deal_comment'];
					$dealData['deal_status'] = $postedData['deal_status'];
					$dealData['deal_updatedby'] = $this->USER->lgn_id;
                    $dealData['deal_updateddate'] = date('Y-m-d H:i:s');
					//echo '<pre>';print_r($postedData);exit;
                    $dealModel->save($dealData, 'deal_id');
                    if ($this->view->mode == 'Add') {
                        $successmessage = 'Deal add successfully';
                    } else {
                        $successmessage = 'Deal updated successfully';
                    }
                    $this->addSuccessMessage($successmessage);
                    $this->_helper->redirector('list', 'deals', 'admin');
                }
            }
        }
        $this->view->compid = $deal_id;
		$this->view->deal_available_to_everyone = $deal_available_to_everyone;
		$this->view->errorMessageArray = $errorMessageArray;
        $this->view->succesMessage = $successmessage;
        $this->view->form = $dealsForm;
    }
	
	public function addclientAction() {
		 
		$clnt_id = "";
		 
		//Load client Model
        $clientModel = new Model_Client();

        if ($this->getRequest()->isPost()) {
            $postdata = $this->_request->getPost();
            $clientData = array();
                    $clientData['clnt_id'] = $clnt_id;
					$clientData['clnt_first_name'] = $postdata['clnt_first_name'];
                    $clientData['clnt_middle_name'] = $postdata['clnt_middle_name'];
                    $clientData['clnt_last_name'] = $postdata['clnt_last_name'];
                    $clientData['clnt_email'] = $postdata['clnt_email'];
					$clientData['clnt_phone'] = $postdata['clnt_phone'];
					$clientData['clnt_addedby'] = $this->USER->lgn_id;
					$clientData['clnt_updatedby'] = $this->USER->lgn_id;
					$clientData['clnt_responsible'] = $this->USER->lgn_id;
					$clientData['clnt_createddate'] = date('Y-m-d H:i:s');
                    $clientData['clnt_updateddate'] = date('Y-m-d H:i:s');
                    $clientData['clnt_status'] = 1;
					$client_last_id = $clientModel->save($clientData, 'clnt_id');
              
            echo $client_last_id;
        }
        exit;
		 
	 }
	 
	 public function getclientlistAction() {
		
        // $areaString = "<option>-- Select Area--</option>";
        if ($this->getRequest()->isPost()) {
            $postedData = $this->_request->getPost();
			
			//Load client Model
			$clientModel = new Model_Client();
			$ClientArray = $clientModel->fetchClient();
			
			if (count($ClientArray) > 0) {
				$clientString = "";
				$selected = "";
				foreach ($ClientArray as $clnt_id => $client_name) {
					
					if ($postedData['client_last_id'] == $clnt_id){
						$selected = "selected";
					}
					
					$clientString .= "<option " . $selected . " value='" . $clnt_id . "'>" . $client_name . "</option>";
				}
			}        
        }
        echo $clientString;
        exit;
    }

    public function deleteAction($ids = Array()) {
		
		//Load deal Model
        $dealModel = new Model_Deals();
		
        if ($this->_getParam('deal_id') && $this->_getParam('deal_id') != '') {
            $deal_id = $this->_getParam('deal_id');

            $dealData = array();
            $dealData = $dealModel->fetchEntryById($deal_id);
            
            $dealModel->deleteDeal($deal_id);
            $this->addSuccessMessage('Deal Successfully Deleted');
            $this->_helper->redirector('list', 'deals', 'admin');
        } else {
            $dealModel->deleteDeal($ids);
            $this->addSuccessMessage('Deal Successfully Deleted');
            $this->_helper->redirector('list', 'deals', 'admin');
        }
    }
}
?>